{% extends 'assets/base.html' %}
{% load static %}

{% block title %}异常检测列表{% endblock %}

{% block extra_css %}
<style>
.anomaly-card {
    border-left: 4px solid #ffc107;
    transition: all 0.3s ease;
}
.anomaly-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.anomaly-card.severity-high {
    border-left-color: #dc3545;
}
.anomaly-card.severity-critical {
    border-left-color: #6f42c1;
}
.anomaly-card.severity-medium {
    border-left-color: #fd7e14;
}
.anomaly-card.severity-low {
    border-left-color: #28a745;
}
.confidence-score {
    font-weight: bold;
    color: #007bff;
}
.filter-card {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-exclamation-triangle"></i> 异常检测列表</h2>
        <div class="btn-group">
            <a href="{% url 'assets:ai_dashboard' %}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> 返回仪表板
            </a>
            <button type="button" class="btn btn-warning" onclick="runAnomalyDetection()">
                <i class="fas fa-search"></i> 运行检测
            </button>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-card">
        <form method="get" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">异常类型</label>
                <select name="type" class="form-select">
                    <option value="">全部类型</option>
                    {% for value, label in anomaly_types %}
                    <option value="{{ value }}" {% if current_filters.type == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">严重程度</label>
                <select name="severity" class="form-select">
                    <option value="">全部程度</option>
                    {% for value, label in severities %}
                    <option value="{{ value }}" {% if current_filters.severity == value %}selected{% endif %}>
                        {{ label }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">状态</label>
                <select name="status" class="form-select">
                    <option value="all" {% if current_filters.status == 'all' %}selected{% endif %}>全部状态</option>
                    <option value="unconfirmed" {% if current_filters.status == 'unconfirmed' %}selected{% endif %}>未确认</option>
                    <option value="confirmed" {% if current_filters.status == 'confirmed' %}selected{% endif %}>已确认</option>
                    <option value="resolved" {% if current_filters.status == 'resolved' %}selected{% endif %}>已解决</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">&nbsp;</label>
                <div class="d-grid">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="fas fa-search"></i> 筛选
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 异常列表 -->
    <div class="row">
        {% if page_obj %}
            {% for anomaly in page_obj %}
            <div class="col-md-6 mb-3">
                <div class="card anomaly-card severity-{{ anomaly.severity }}" data-id="{{ anomaly.id }}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title mb-0">
                                <a href="{% url 'assets:asset_detail' anomaly.asset.pk %}" class="text-decoration-none">
                                    {{ anomaly.asset.name }}
                                </a>
                            </h5>
                            <div class="btn-group btn-group-sm">
                                {% if not anomaly.is_confirmed %}
                                <button class="btn btn-warning" onclick="handleAnomaly({{ anomaly.id }}, 'confirm')" title="确认异常">
                                    <i class="fas fa-check"></i>
                                </button>
                                {% endif %}
                                {% if anomaly.is_confirmed and not anomaly.is_resolved %}
                                <button class="btn btn-success" onclick="handleAnomaly({{ anomaly.id }}, 'resolve')" title="解决异常">
                                    <i class="fas fa-check-double"></i>
                                </button>
                                {% endif %}
                            </div>
                        </div>
                        
                        <p class="card-text text-muted">{{ anomaly.description }}</p>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <small class="text-muted">异常类型:</small><br>
                                <span class="badge bg-info">{{ anomaly.get_anomaly_type_display }}</span>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">严重程度:</small><br>
                                <span class="badge bg-{{ anomaly.severity }}">{{ anomaly.get_severity_display }}</span>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <small class="text-muted">置信度:</small><br>
                                <span class="confidence-score">{{ anomaly.confidence_score|floatformat:1 }}</span>
                            </div>
                            <div class="col-6">
                                <small class="text-muted">检测时间:</small><br>
                                <small>{{ anomaly.detected_at|date:"Y-m-d H:i" }}</small>
                            </div>
                        </div>
                        
                        <div class="mb-2">
                            <small class="text-muted">资产信息:</small><br>
                            <span class="badge bg-secondary">{{ anomaly.asset.asset_number }}</span>
                            {% if anomaly.asset.department %}
                            <span class="badge bg-outline-secondary">{{ anomaly.asset.department.name }}</span>
                            {% endif %}
                        </div>
                        
                        <div class="mb-2">
                            <small class="text-muted">检测算法:</small><br>
                            <code class="small">{{ anomaly.detection_algorithm }}</code>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                {% if anomaly.is_resolved %}
                                <span class="badge bg-success"><i class="fas fa-check-double"></i> 已解决</span>
                                {% elif anomaly.is_confirmed %}
                                <span class="badge bg-warning"><i class="fas fa-check"></i> 已确认</span>
                                {% else %}
                                <span class="badge bg-danger"><i class="fas fa-exclamation"></i> 待确认</span>
                                {% endif %}
                            </div>
                            {% if anomaly.resolved_at %}
                            <small class="text-muted">
                                <i class="fas fa-clock"></i> 
                                解决时间: {{ anomaly.resolved_at|date:"Y-m-d H:i" }}
                            </small>
                            {% endif %}
                        </div>
                        
                        {% if anomaly.resolution_notes %}
                        <div class="mt-2">
                            <small class="text-muted">处理备注:</small><br>
                            <small class="text-info">{{ anomaly.resolution_notes }}</small>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="col-12">
                <div class="text-center py-5">
                    <i class="fas fa-shield-alt fa-4x text-muted mb-3"></i>
                    <h4 class="text-muted">暂无异常检测数据</h4>
                    <p class="text-muted">点击"运行检测"按钮来执行异常检测</p>
                    <button type="button" class="btn btn-warning" onclick="runAnomalyDetection()">
                        <i class="fas fa-search"></i> 运行检测
                    </button>
                </div>
            </div>
        {% endif %}
    </div>

    <!-- 分页 -->
    {% if page_obj.has_other_pages %}
    <nav aria-label="异常检测列表分页">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    上一页
                </a>
            </li>
            {% endif %}
            
            {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
            <li class="page-item active">
                <span class="page-link">{{ num }}</span>
            </li>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
            <li class="page-item">
                <a class="page-link" href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    {{ num }}
                </a>
            </li>
            {% endif %}
            {% endfor %}
            
            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">
                    下一页
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
</div>

<!-- 运行检测模态框 -->
<div class="modal fade" id="detectionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">运行异常检测</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="detectionForm">
                    <div class="mb-3">
                        <label class="form-label">检测类型</label>
                        <select name="type" class="form-select" required>
                            <option value="all">全部类型</option>
                            <option value="usage">使用模式异常</option>
                            <option value="frequency">维修频率异常</option>
                            <option value="cost">成本异常</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">指定资产 (可选)</label>
                        <select name="asset_id" class="form-select">
                            <option value="">全部资产</option>
                            <!-- 这里可以通过AJAX加载资产列表 -->
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" onclick="submitDetection()">开始检测</button>
            </div>
        </div>
    </div>
</div>

<!-- 处理异常模态框 -->
<div class="modal fade" id="handleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理异常</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="anomalyDescription"></p>
                <div class="form-group">
                    <label>处理备注</label>
                    <textarea class="form-control" id="handleNotes" rows="3" placeholder="请输入处理备注..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" id="confirmBtn" onclick="confirmHandle()">确认异常</button>
                <button type="button" class="btn btn-success" id="resolveBtn" onclick="resolveHandle()">解决异常</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentAnomalyId = null;
let currentAction = null;

// 运行异常检测
function runAnomalyDetection() {
    const modal = new bootstrap.Modal(document.getElementById('detectionModal'));
    modal.show();
}

function submitDetection() {
    const form = document.getElementById('detectionForm');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    showLoading('正在运行异常检测...');
    
    fetch('{% url "assets:ai_run_anomaly_detection" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            showAlert('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('detectionModal')).hide();
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        hideLoading();
        showAlert('error', '异常检测失败: ' + error.message);
    });
}

// 处理异常
function handleAnomaly(id, action) {
    currentAnomalyId = id;
    currentAction = action;
    
    const modal = new bootstrap.Modal(document.getElementById('handleModal'));
    const card = document.querySelector(`[data-id="${id}"]`);
    const description = card.querySelector('.card-text').textContent;
    
    document.getElementById('anomalyDescription').textContent = description;
    document.getElementById('handleNotes').value = '';
    
    // 根据操作类型显示/隐藏按钮
    const confirmBtn = document.getElementById('confirmBtn');
    const resolveBtn = document.getElementById('resolveBtn');
    
    if (action === 'confirm') {
        confirmBtn.style.display = 'inline-block';
        resolveBtn.style.display = 'none';
    } else {
        confirmBtn.style.display = 'none';
        resolveBtn.style.display = 'inline-block';
    }
    
    modal.show();
}

function confirmHandle() {
    submitHandle('confirm');
}

function resolveHandle() {
    submitHandle('resolve');
}

function submitHandle(action) {
    const notes = document.getElementById('handleNotes').value;
    
    fetch(`/assets/ai/anomalies/${currentAnomalyId}/handle/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            action: action,
            notes: notes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('handleModal')).hide();
            
            // 更新卡片状态
            const card = document.querySelector(`[data-id="${currentAnomalyId}"]`);
            if (card) {
                const statusArea = card.querySelector('.d-flex.justify-content-between.align-items-center div');
                const buttons = card.querySelector('.btn-group');
                
                if (action === 'confirm') {
                    statusArea.innerHTML = '<span class="badge bg-warning"><i class="fas fa-check"></i> 已确认</span>';
                    // 更新按钮为解决按钮
                    buttons.innerHTML = '<button class="btn btn-success btn-sm" onclick="handleAnomaly(' + currentAnomalyId + ', \'resolve\')" title="解决异常"><i class="fas fa-check-double"></i></button>';
                } else if (action === 'resolve') {
                    statusArea.innerHTML = '<span class="badge bg-success"><i class="fas fa-check-double"></i> 已解决</span>';
                    buttons.remove();
                }
                
                // 添加处理备注
                if (notes) {
                    const cardBody = card.querySelector('.card-body');
                    const notesDiv = document.createElement('div');
                    notesDiv.className = 'mt-2';
                    notesDiv.innerHTML = `
                        <small class="text-muted">处理备注:</small><br>
                        <small class="text-info">${notes}</small>
                    `;
                    cardBody.appendChild(notesDiv);
                }
            }
        } else {
            showAlert('error', data.message);
        }
    })
    .catch(error => {
        showAlert('error', '处理异常失败: ' + error.message);
    });
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showLoading(message) {
    const loading = document.createElement('div');
    loading.id = 'loading-overlay';
    loading.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center';
    loading.style.backgroundColor = 'rgba(0,0,0,0.5)';
    loading.style.zIndex = '9999';
    loading.innerHTML = `
        <div class="bg-white p-4 rounded text-center">
            <div class="spinner-border text-warning mb-2"></div>
            <div>${message}</div>
        </div>
    `;
    document.body.appendChild(loading);
}

function hideLoading() {
    const loading = document.getElementById('loading-overlay');
    if (loading) {
        loading.remove();
    }
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}
</script>
{% endblock %}